package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.CheckGroupService;

import com.itheima.dao.CheckGroupDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
* 检查组服务层
* */
@Service(interfaceClass = CheckGroupService.class)
@Transactional
public class CheckGroupServiceImpl implements CheckGroupService {
    @Autowired
    private CheckGroupDao checkGroupDao;

    //新增检查组，同时检查组要关联检查项
    @Override
    public void add(CheckGroup checkGroup, Integer[] checkitemIds) {

        //新增检查组，操作t_checkgroup表
        checkGroupDao.add(checkGroup);
        //设置检查组合和检查项的关联关系
        Integer checkGroupId = checkGroup.getId();
        this.setCheckGroupAndCheckItem(checkGroupId,checkitemIds );

    }

    //检查组分页查询
    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        //从第几页
        Integer currentPage = queryPageBean.getCurrentPage();
        //查几条
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        //分页助手完成分页会更简单

        PageHelper.startPage(currentPage, pageSize);

        Page<CheckGroup> page = checkGroupDao.findByCondition(queryString);
        return new PageResult(page.getTotal(), page.getResult());
    }

    //检查组编辑查询id
    @Override
    public CheckGroup findById(Integer id) {
        return checkGroupDao.findById(id);
    }

    //检查组编辑查询(复选框回写)
    @Override
    public List<Integer> finds(Integer id) {
        return checkGroupDao.finds(id);
    }

    //检查组编辑添加,同时关联检查项
    public void edit(CheckGroup checkGroup, Integer[] checkitemIds) {
        //编辑修改基本信息
        checkGroupDao.edit(checkGroup);
        //根据检查组id删除中间表数据（清理原有关联关系)
        checkGroupDao.deleteAssociation(checkGroup.getId());

        Integer checkGroupId = checkGroup.getId();
        this.setCheckGroupAndCheckItem(checkGroupId,checkitemIds );
    }
//查询所有检查组(套餐管理)
    @Override
    public List<CheckGroup> findAll() {
        return checkGroupDao.findAll();
    }
/*//删除检查项
    @Override
    public void deleteById(Integer id) {

        checkGroupDao.deleteById(id);

    }*/
    //建立检查组和检查项关联关系--add edit
    public void setCheckGroupAndCheckItem(Integer checkGroupId,Integer[] checkitemIds) {
        if (checkitemIds != null && checkitemIds.length > 0) {
            for (Integer checkitemId : checkitemIds) {
                Map<String, Integer> map = new HashMap<>();
                map.put("checkgroupId", checkGroupId);
                map.put("checkitemId", checkitemId);
                checkGroupDao.setCheckGroupAndCheckItem(map);
            }
        }
    }
}
